 <!--
* description: 实时统计
* author: wangml
* createdDate: 2020-12-10
-->
<template>
  <section class="cartypeQuery">
    <el-dialog
      id="cartypeq"
      v-dialogDrag
      title="月销售计划实时统计"
      :visible.sync="popupsVisible"
      width="70%"
      center
      :append-to-body="true"
      :lock-scroll="true"
      :before-close="handleClose"
    >
      <dialogHeader
        slot="title"
        :title="'月销售计划实时统计'"
        :style-type="$store.state.app.dialogType"
      />

      <template v-for="comps in coms">
        <div :key="comps.compKey" class="filter-container filter-params">
          <h3 v-if="comps.title" :style="styleObj">{{ comps.title }}</h3>
          <el-row ref="vailComponentList1" :gutter="26">
            <component
              :is="comp.component"
              v-for="comp in comps.data.filter(o => o.isMust === true)"
              :ref="comp.isRequire ? comp.isRequire+ comp.compKey : comp.compKey"
              :key="comp.compKey"
              :validrule="comp.validrule"
              :code-field="comp.codeField"
              :text-field="comp.textField"
              :popups-key="comp.compKey"
              :code="formField[comp.codeField]"
              :disabled="comp.disabled"
              :is-require="comp.isRequire"
              :is-mul="comp.isMul"
              :span="comp.span || 24"
              :label-name="comp.labelName"
              :lookuptype="comp.lookuptype"
              :data-to-object="comp.dataToObj"
              :date-options-type="comp.dateOptionsType"
              :options="comp.options"
              :o-fields="comp.oFields"
              :date-type="comp.dateType"
              :format="comp.format"
              @changeCode="getComponentCode"
              @focusCode="getFocusCode"
            />
          </el-row>
        </div>
      </template>
      <div class="btns">
        <el-button
          size="mini"
          type="normal"
          @click="reset1"
        >{{ $t('sys.button.reset') }}
        </el-button>
        <el-button
          size="mini"
          type="primary"
          icon="iconfont  icon-confirm"
          @click="sendCode"
        >查询
        </el-button>
      </div>
      <el-divider />
      <div class="charss">
        <div id="carColor" ref="carColor" style="height: 300px; width: 90%" />
        <el-divider />
        <div id="carConfig" ref="carConfig" style="height: 300px; width: 90%" />
        <el-divider />
        <div id="carIncolor" ref="carIncolor" style="height: 300px; width: 90%" />
        <el-divider />
        <div id="carSeries" ref="carSeries" style="height: 300px; width: 90%" />
        <el-divider />
        <div id="optionalPackage" ref="optionalPackage" style="height: 300px; width: 90%" />
        <el-divider />
      </div>
    </el-dialog>
  </section>
</template>
<script>

import Vue from 'vue'
import echarts from 'echarts'
import { formMixins } from '@/components/mixins/formMixins'
import { requestRestful } from '@/api/commonRequest'
import api from '@/api/planReport'

export default {
  name: 'RealTimeStatistics',
  components: {
    lableName: () => import('@/components/lableName'), // 标题溢出样式组件
    dialogHeader: () => import('@/components/dialogHeader') // 弹窗标题,
  },
  mixins: [formMixins],
  props: {
    popupsVisible: { type: Boolean, default: false },
    code: { type: String, default: '' },
    comType: { type: String, default: '' },
    codeField: { type: String, default: '' },
    popupsKey: { type: String, default: '' },
    isMul: { type: Boolean, default: true },
    validrule: {
      type: Object,
      default: () => {}
    }
  },
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData(
      // 同时加载当前页面和编辑框页面的配置
      [to.path, ''],
      function() {
        next()
      })
  },
  data() {
    const viewPageCode = this.$route.path
    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])
    return {
      // apiStyle: 'restful',
      // ruleSettingShow: false,
      // h3标题行内样式
      tableComponents: null,
      genCodeFiled: null,
      styleObj: { borderLeft: null },
      coms: [
        {
          // title: '保险费发票',
          data: [
            {
              compKey: 'compKey1',
              labelName: '制定月份：',
              codeField: 'makingMonth',
              component: () => import('@/components/org/datePicker/datePicker.vue'),
              format: 'yyyy-MM',
              dateType: 'month',
              type: 'dropdownList',
              isMust: true,
              span: 12
            },
            {
              compKey: 'compKey2',
              labelName: '计划月份：',
              codeField: 'planMonth',
              format: 'yyyy-MM',
              component: () => import('@/components/org/datePicker/datePicker.vue'),
              dateType: 'month',
              isMust: true,
              span: 12
            }

          ]
        }
      ],
      curPopupsVisible: this.popupsVisible,
      formField: {
        makingMonth: '',
        planMonth: ''
      },
      charss: [
        { ref: 'carColor', title: '车身颜色' },
        { ref: 'carConfig', title: '车型配置' },
        { ref: 'carIncolor', title: '内饰颜色' },
        { ref: 'carSeries', title: '车系' },
        { ref: 'optionalPackage', title: '选装包' }]
    }
  },
  watch: {
    popupsVisible: {
      handler(val) {
        if (val) {
          this.$nextTick(() => {
            // this.charss.forEach(item => {
            //   this.echartsInit(item.ref, item.title)
            // })
            this.sendCode()
          })
        }
      },
      immediate: true
    }
  },
  mounted() {
    this.setColor()
  },

  methods: {
    echartsInit(chars, title, nameList = [], numberList = []) {
      const option = {
        title: { text: title },
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' }
        },
        legend: { /*  data: [ '2012年']*/ },
        grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
        xAxis: { type: 'value', boundaryGap: [0, 0.01] },
        yAxis: {
          type: 'category',
          data: nameList.reverse(),
          axisLabel: {
            interval: 0
          }
        },
        series: [
          {
            name: '数量',
            type: 'bar',
            label: {
              show: true,
              color: '#000000',
              position: 'right'
            },
            itemStyle: {
              normal: {
                color: '#00B4E1'
              }
            },
            data: numberList.reverse()
          }
        ]
      }
      const StatisticalTable = this.$refs[chars]
      echarts.init(StatisticalTable).setOption(option)
    },
    onCreated() {
      if (this.formField === null) {
        this.formField = { carBrandCode: '' }
      }
    },
    // 重置
    reset1() {
      this.reset()
    },
    // 获取数据
    sendCode() {
      requestRestful({
        // 请求url
        apiUrl: api.hqStaticsCount.APIUrl,
        // 请求参数
        variables: this.formField
      }).then(res => {
        const datas = res.rows
        let index = 0
        for (const a in datas) {
          if (datas.carColor.length > 0) {
            const attrs = Object.keys(datas[a][0])
            const gen = this.genValArr(datas[a])
            this.echartsInit(this.charss[index].ref, this.charss[index].title, gen(attrs[1]), gen(attrs[0]))
          } else {
            this.echartsInit(this.charss[index].ref, this.charss[index].title)
          }
          index++
        }
      })
    },
    genValArr: (array) => (attr) => array.map(item => item[attr]),
    genUtil: (array) => (attr) => array.reduce((p, c) => {
      p[c[attr]] = ''
      return p
    }, {}),
    // 设置h3标题颜色
    setColor() {
      const nowSystemColor = this.$store.getters.nowTheme.backgroundColor
      this.styleObj.borderLeft = `5px solid ${nowSystemColor}`
    },

    handleClose() {
      this.$confirm(`确认关闭？`)
        .then(_ => {
          this.$emit('update:popupsVisible', false)
          // eslint-disable-next-line no-undef
          done()
        })
        .catch(_ => {})
    }

  }
}
</script>

<style lang="css" scoped>
  div.filter-container {
    margin-top: 25px;
  }
  >>> div.btns {
    padding: 10px 14px;
    overflow: hidden;
  }
  >>> div.btns .el-button {
    margin: 3px 10px;
    float: right;
  }
  h3 {
    padding-left: 10px;
    text-align: left;
    font-weight: 600;
  }

  h3 button.el-button {
    float: right;
    margin-right: 10px;
  }

  .dialog-footer {
    float: right;
  }
  >>>.el-dialog__footer {
    overflow: hidden;
    padding: 10px 24px;
  }
  div.charss {
    max-height: 500px;
    overflow-y: auto;
    overflow-x: hidden;
  }
</style>
